package edu.gdkm.ssm.controller;

import edu.gdkm.ssm.domain.Product;
import edu.gdkm.ssm.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("product")
public class ProductController {

    @Autowired
    private IProductService productService;

    @PostMapping("save.do")
    @Secured("ROLE_ADMIN") // 不能省略ROLE_前缀
    public String save(Product product){
        this.productService.save(product);
        return "redirect:findAll.do";
    }

    @GetMapping("findAll.do")
    @RolesAllowed("ADMIN") // 表示拥有ADMIN角色才可以访问此方法 JSR-250可以省略ROLE_前缀
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<Product> products = productService.findAll();
        System.out.println(products);
        mv.addObject("productList", products);
        mv.setViewName("product-list");
        return mv;
    }
}
